package com.mylg.craw.house.government.util;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Base64;

public class Base64ToImage {

    public static void output(String base64ImageString, String file) {
        // 移除数据URL的前缀（如果有的话）
        if (base64ImageString.contains(",")) {
            base64ImageString = base64ImageString.split(",")[1];
        }

        // 解码 Base64 字符串为字节数组
        byte[] imageBytes = Base64.getDecoder().decode(base64ImageString);

        // 将字节数组写入到文件
        try (OutputStream os = new FileOutputStream(file)) {
            os.write(imageBytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String input(String file) {
        File imageFile = new File(file);
        BufferedImage bufferedImage;
        try {
            bufferedImage = ImageIO.read(imageFile);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "png", baos);
            byte[] imageBytes = baos.toByteArray();
            return Base64.getEncoder().encodeToString(imageBytes);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
